unit CapturarImg;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls, ExtCtrls, DBCtrls, Buttons, Grids, DBGrids, DB, DSUtil,
  ApoEnv, ApWin, ApConn, ApoDSet,jpeg, IniFiles, DSPack, DirectShow9;

type
  TfrmCaptura = class(TForm)
    FilterGraph1: TFilterGraph;
    SampleGrabber1: TSampleGrabber;
    Filter1: TFilter;
    Button1: TButton;
    Image1: TImage;
    VideoWindow1: TVideoWindow;
    Timer1: TTimer;
    Button2: TButton;
    procedure FormShow(Sender: TObject);
    procedure Button1Click(Sender: TObject);
    procedure Button2Click(Sender: TObject);
  private
    { Private declarations }
    procedure ApagarImagem(codigo : string);
  public
    { Public declarations }
    codigo : string;
    FPastaPadrao: string;
  end;

var
  frmCaptura: TfrmCaptura;
  SysDev : TSysDevEnum;
implementation

uses Math;

{$R *.dfm}

procedure TfrmCaptura.ApagarImagem(codigo: string);
begin
  if FileExists(FPastaPadrao + codigo + '.jpg') then
    DeleteFile(FPastaPadrao + codigo + '.jpg');
end;

procedure TfrmCaptura.FormShow(Sender: TObject);
begin
  SysDev := TSysDevEnum.Create(CLSID_VideoInputDeviceCategory);
  VideoWindow1.Visible := true;
  Image1.Visible := false;
  FilterGraph1.ClearGraph;
  FilterGraph1.Active := false;
  Filter1.BaseFilter.Moniker := SysDev.GetMoniker(0);
  FilterGraph1.Active := true;
  with FilterGraph1 as ICaptureGraphBuilder2 do
  begin
    CheckDSError(RenderStream(@PIN_CATEGORY_PREVIEW , nil, Filter1 as IBaseFilter,SampleGrabber1 as IBaseFilter, VideoWindow1 as IbaseFilter));
  end;
  FilterGraph1.Play;
end;

procedure TfrmCaptura.Button1Click(Sender: TObject);
var
  ti : integer ;
begin
  Image1.Visible := true;
  SampleGrabber1.GetBitmap(Image1.Picture.Bitmap);
  VideoWindow1.Visible := false;
  ti := 0;
  while (ti <= 3000) do
  begin
    Application.ProcessMessages;
    sleep(ti);
    ti := ti + 1000;
    Update;
    if (ti = 3000) then begin
      Image1.Visible := false;
      VideoWindow1.Visible := true;
    end;
  end;
end;

procedure TfrmCaptura.Button2Click(Sender: TObject);
var
  jpeg_file : TJPEGImage;
begin
  ApagarImagem(codigo);
  jpeg_file := TJPEGImage.Create;
  jpeg_file.Assign(Image1.Picture.Bitmap);
  jpeg_file.SaveToFile(FPastaPadrao + codigo + '.jpg');
  jpeg_file.Free;
  frmCaptura.Close;
end;

end.
